package com.xxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxx.dao.CartDao;
import com.xxx.dao.ProductDao;
import com.xxx.pojo.Cart;
import com.xxx.pojo.Product;
import com.xxx.service.CartService;
import com.xxx.service.ex.DeleteException;
import com.xxx.service.ex.InsertException;
import com.xxx.service.ex.UpdatException;
import com.xxx.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartDao cartDao;
    @Autowired
    private ProductDao productDao;
    //添加商品到购物车功能
    @Override
    public void addToCart(Integer uid, Integer pid, Integer amount, String username) {
        Map<String, Object> map=new HashMap<>();
        map.put("uid",uid);
        map.put("pid",pid);
        List<Cart> result = cartDao.selectByMap(map);
        if(result.size()==0){//表示该商品不存在于购物车中
            //执行插入
            Cart cart=new Cart();
            cart.setUid(uid);
            cart.setPid(pid);
            //获取价格
            Product product = productDao.selectById(pid);
            cart.setPrice(product.getPrice());
            cart.setNum(amount);

            cart.setCreatedUser(username);
            cart.setCreatedTime(new Date());
            cart.setModifiedUser(username);
            cart.setModifiedTime(new Date());

            int row = cartDao.insert(cart);
            if(row!=1){
                throw new InsertException("(购物车保存商品时)插入数据时产生未知异常");
            }
        }else {//该商品存在于购物车 增加num值
            result.get(0).setNum(result.get(0).getNum()+amount);
            Cart cart=new Cart();
            cart.setNum(result.get(0).getNum());
            cart.setModifiedUser(username);
            cart.setModifiedTime(new Date());
            LambdaQueryWrapper<Cart> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Cart::getCid,result.get(0).getCid());
            int row = cartDao.update(cart,wrapper);
            if(row!=1){
                throw new UpdatException("(购物车修改商品数量时)更新数据出现未知异常");
            }
        }
    }

    //显示购物车商品功能

    @Override
    public List<CartVo> getCartProducts(Integer uid) {
        Map<String, Object> map=new HashMap<>();
        map.put("uid",uid);
        //通过uid获取cart表中的数据
        List<Cart> result = cartDao.selectByMap(map);
        if(result.size()==0){
            return null;
        }
        //通过cart表中的pid 获取商品的title image
        //CartVoList存储要返回的数据
        List<CartVo> cartVoList=new ArrayList<>();
        //后加操作 如果购物车某个商品 被在购物车中数量减少为0 则刷新页面时将这条数据删除
        Iterator<Cart> iterator = result.iterator();
        while (iterator.hasNext()){
            Cart cart =iterator.next();
            if(cart.getNum()==0){
                //执行删除操作
                map.clear();
                map.put("cid",cart.getCid());
                int row = cartDao.deleteByMap(map);
                if (row!=1){
                    throw new DeleteException("(刷新页面删除购物车数量为0操作时)删除数据时产生未知异常");
                }
                iterator.remove();
                continue;
            }

            Product product = productDao.selectById(cart.getPid());
            CartVo cartVo=new CartVo();
            cartVo.setCid(cart.getCid());
            cartVo.setPid(cart.getPid());
            cartVo.setImage(product.getImage());
            cartVo.setTitle(product.getTitle());
            cartVo.setPrice(cart.getPrice());
            cartVo.setNum(cart.getNum());
            cartVo.setRealPrice(product.getPrice());

            cartVoList.add(cartVo);
        }
        return cartVoList;
    }

    //修改购物车某个商品数量功能
    @Override
    public int changeNum(Integer cid,String username,Integer amount,String option) {
        Map<String, Object> map=new HashMap<>();
        map.put("cid",cid);
        List<Cart> result = cartDao.selectByMap(map);

        Cart cart=new Cart();
        if("+".equals(option)){ //增加操作
            cart.setNum(result.get(0).getNum()+amount);
        }else{//减少操作
            //当数据库中num为0时 停止减少操作 返回前端数据0
            if (result.get(0).getNum()==0){
                return 0;
            }
            cart.setNum(result.get(0).getNum()-amount);
        }

        cart.setModifiedUser(username);
        cart.setModifiedTime(new Date());

        LambdaQueryWrapper<Cart> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Cart::getCid,cid);
        int row = cartDao.update(cart, wrapper);
        if(row!=1){
            throw new UpdatException("(增加购物车商品数量时)更新数据时出现未知异常");
        }
        if("+".equals(option)){ //增加操作
            return result.get(0).getNum()+amount;
        }
        return result.get(0).getNum()-amount;
    }


    //批量删除购物车商品功能
    @Override
    public void deleteProducts(Integer[] cids) {
        Map<String, Object> map=new HashMap<>();
        for (Integer cid : cids) {
            map.clear();
            map.put("cid",cid);
            int row = cartDao.deleteByMap(map);
            if(row!=1) {
                throw new DeleteException("(批量删除购物车数据时)删除数据时出现未知异常");
            }
        }
    }

    //通过cids获取商品总价功能
    @Override
    public Float getTotalPriceByCids(Integer[] cids) {
        float totalPrice=0;
        Map<String, Object> map=new HashMap<>();
        for (Integer cid : cids) {
            map.put("cid",cid);
            List<Cart> result = cartDao.selectByMap(map);
            totalPrice=totalPrice+Float.parseFloat(result.get(0).getPrice())*(result.get(0).getNum());
        }
        return totalPrice;
    }

    //通过cids获取订单页面要显示的数据 功能
    @Override
    public List<CartVo> getOrderList(Integer[] cids) {
        List<CartVo> cartVoList=new ArrayList<>();

        Map<String, Object> map=new HashMap<>();
        for (int i=0;i<cids.length;i++) {
            //通过cid查询pid price num
            map.put("cid",cids[i]);
            List<Cart> cartList = cartDao.selectByMap(map);
            if(cartList.get(0).getNum()==0){//后加功能  数量为0 订单页面不会显示改商品
                continue;
            }
            //通过pid查询title image
            Product product = productDao.selectById(cartList.get(0).getPid());

            //存储单个cartVo
            CartVo cartVo=new CartVo();
            cartVo.setPrice(cartList.get(0).getPrice());
            cartVo.setNum(cartList.get(0).getNum());
            cartVo.setTitle(product.getTitle());
            cartVo.setImage(product.getImage());
            //添加到集合
            cartVoList.add(cartVo);
        }
        return cartVoList;
    }
}
